chrome.runtime.onInstalled.addListener(() => {
  chrome.contextMenus.create({
    id: "translateSelection",
    title: "翻译选中文本",
    contexts: ["selection"]
  });
});

chrome.contextMenus.onClicked.addListener((info, tab) => {
  if (info.menuItemId === "translateSelection") {
    chrome.tabs.sendMessage(tab.id, {
      action: "translate",
      text: info.selectionText
    });
  }
});

chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
  if (request.action === "translateText") {
    // 调用本地翻译服务器
    console.log('发送翻译请求:', request.text);
    
    fetch('http://localhost:5000/translate', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({text: request.text})
    })
    .then(response => {
      if (!response.ok) {
        throw new Error('服务器响应错误: ' + response.status);
      }
      return response.json();
    })
    .then(data => {
      console.log('接收到翻译结果:', data);
      if (data.translation) {
        sendResponse({translatedText: data.translation});
      } else if (data.error) {
        sendResponse({translatedText: '翻译错误: ' + data.error});
      } else {
        sendResponse({translatedText: '收到无效的翻译结果'});
      }
    })
    .catch(error => {
      console.error('翻译服务器连接失败:', error);
      sendResponse({translatedText: '翻译服务暂时不可用，请确保本地服务器正在运行: ' + error.message});
    });
    
    // 对于异步操作，必须返回true
    return true;
  }
});